package uk.co.q3c.deplan.server.unit.domain.util;

import java.util.Calendar;
import java.util.Date;

import org.apache.log4j.Logger;
import org.testng.Assert;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;

import uk.co.q3c.deplan.client.util.Q3DateUtil;
import uk.co.q3c.deplan.server.domain.util.Q3CalendarUtil;
import uk.co.q3c.deplan.server.util.Q3Calendar;

/**
 * {@link Q3DateUtil }
 * 
 * @author DSowerby 26 Nov 2008
 * 
 */
@Test
public class Q3DateUtil_UT {
	transient protected final Logger logger = Logger.getLogger(getClass().getName());

	@BeforeMethod
	public void beforeMethod() {

	}

	@AfterMethod
	public void afterMethod() {

	}

	/**
	 * Test points beginning, end and midday. 1 mS each side of midday, by comparing to <code>ref</code>
	 */
	public void doit() {
		Q3Calendar cal = new Q3Calendar();
		cal.set(2009, 0, 1, 0, 0, 0);
		cal.set(Calendar.MILLISECOND, 0);
		long ref = cal.getTimeInMillis();

		// 1 mS from start
		cal.set(Calendar.MILLISECOND, 1);
		Date d = Q3CalendarUtil.dateOnly_date(cal.getTime());
		Assert.assertEquals(ref, d.getTime());

		// midday
		cal.set(2009, 0, 1, 12, 0, 0);
		cal.set(Calendar.MILLISECOND, 0);
		d = Q3CalendarUtil.dateOnly_date(cal.getTime());
		Assert.assertEquals(ref, d.getTime());

		// 1mS before midday
		cal.set(2009, 0, 1, 12, 0, 0);
		logger.info(cal.getTimeInMillis());
		cal.set(Calendar.MILLISECOND, -1);
		logger.info(cal.getTimeInMillis());
		d = Q3CalendarUtil.dateOnly_date(cal.getTime());
		Assert.assertEquals(ref, d.getTime());

		// 1mS after midday
		cal.set(2009, 0, 1, 12, 0, 0);
		logger.info(cal.getTimeInMillis());
		cal.set(Calendar.MILLISECOND, 1);
		logger.info(cal.getTimeInMillis());
		d = Q3CalendarUtil.dateOnly_date(cal.getTime());
		Assert.assertEquals(ref, d.getTime());

		// 1mS before end of day
		cal.set(2009, 0, 2, 0, 0, 0);
		logger.info(cal.getTimeInMillis());
		cal.set(Calendar.MILLISECOND, -11);
		logger.info(cal.getTimeInMillis());
		d = Q3CalendarUtil.dateOnly_date(cal.getTime());
		Assert.assertEquals(ref, d.getTime());

	}

	public void dateKey() {
		Q3Calendar cal = new Q3Calendar();
		// round trip
		cal.set(2009, 0, 2, 0, 43, 0);
		String dateKey = "20090102";
		Assert.assertEquals(Q3DateUtil.dateToKey(cal.getTime()), dateKey);
		cal.setTimeInMillis(0);
		cal.set(2009, 5, 6, 0, 0, 0);
		String key = Q3DateUtil.dateToKey(cal.getTime());
		Assert.assertEquals(cal.getTimeInMillis(), Q3DateUtil.keyToDate(key).getTime());

		dateKey = "20090910";
		Date d = Q3DateUtil.keyToDate(dateKey);
		String returnedKey = Q3DateUtil.dateToKey(d);
		Assert.assertEquals(dateKey, returnedKey);

	}

	public void dateAndCal() {
		Date date = new Date();
		Assert.assertEquals(Q3CalendarUtil.startOfDay_calendar(date).getTime(), Q3DateUtil.startOfDay_date(date));
	}

}
